﻿using System;
using System.Data;
using System.Data.SQLite;
using System.IO;

namespace AutoCryCJService
{
    public class SQLiteHelper
    {
        private SQLiteConnection connection;

        public SQLiteHelper(string dbName)
        {
            connection = new SQLiteConnection($"Data Source={AppDomain.CurrentDomain.BaseDirectory + @"\" + dbName};Version=3;");
            connection.Open();
        }

        public void Close()
        {
            connection.Close();
        }

        /// <summary>
        /// 执行语句，返回受影响行数
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public int ExecuteUpdate(string sql)
        {
            using (SQLiteCommand command = new SQLiteCommand(sql, connection))
            {
                return command.ExecuteNonQuery();
            }
        }

        public int ExecuteUpdate(string sql, params SQLiteParameter[] commandParameters)
        {
            using (SQLiteCommand command = new SQLiteCommand(sql, connection))
            {
                if (commandParameters.Length > 0)
                {
                    foreach (SQLiteParameter parm in commandParameters)
                        command.Parameters.Add(parm);
                }
                return command.ExecuteNonQuery();
            }
        }




        /// <summary>
        /// 返回第一行第一列
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public object ExecuteScalar(string sql)
        {
            using (SQLiteCommand command = new SQLiteCommand(sql, connection))
            {
                return command.ExecuteScalar();
            }
        }


        public SQLiteDataReader ExecuteReader(string sql)
        {
            using (SQLiteCommand command = new SQLiteCommand(sql, connection))
            {
                return command.ExecuteReader();
            }
        }
        /// <summary>
        /// 获取DataTable数据
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public DataTable ExecuteDataTable(string sql)
        {
            using (SQLiteCommand command = new SQLiteCommand(sql, connection))
            {
                using (SQLiteDataAdapter adapter = new SQLiteDataAdapter(command))
                {
                    DataTable dataTable = new DataTable();
                    adapter.Fill(dataTable);
                    return dataTable;
                }
            }
        }
    }


}
